
/*
 * object translations comes from '/web/bundles/user/js/translations/translations.js'
 */

function checkRegisterForm(language)
{
    $('#register_username_error_msg').html(' ');
    $('#register_email_error_msg').html(' ');
    $('#register_password_error_msg').html(' ');
    $('#register_confirm_password_error_msg').html(' ');
    checkUsername(language);
}

function checkUsername(language)
{
    if(isEmpty('register_username'))
        $('#register_username_error_msg').append('<li>' + translations['messages'][language]['username_empty'] + '</li>');
    else
    {
        existsEntity
        (
            'User', 
            {"username" : $('#register_username').val()},
            function(is_set)
            {
                if(!is_set)
                    checkEmail(language);
                else
                    $('#register_username_error_msg').append('<li>' + translations['messages'][language]['username_in_use'] + '</li>');
            }
        );
    }
}

function checkEmail(language)
{
    if(isEmpty('register_email') || !isValidEmail('register_email'))
        $('#register_email_error_msg').append('<li>' + translations['messages'][language]['email_invalid'] + '</li>');
    else
    {
        existsEntity
        (
            'User', 
            {"email" : $('#register_email').val()},
            function(is_set)
            {
                if(!is_set)
                    checkRest(language);
                else
                    $('#register_email_error_msg').append('<li>' + translations['messages'][language]['email_in_use'] + '</li>');
            }
        );
    }
}

function checkRest(language)
{
    var err;
    
    if(isEmpty('register_password'))
    {
        err = true;
        $('#register_password_error_msg').append('<li>' + translations['messages'][language]['password_empty'] + '</li>');
    }
    else if(!isSignCountInRange('register_password', 6))
    {
        err = true;
        $('#register_password_error_msg').append('<li>' + translations['messages'][language]['password_too_short'] + '</li>');
    }
    
    if(isEmpty('register_confirm_password'))
    {
        err = true;
        $('#register_confirm_password_error_msg').append('<li>' + translations['messages'][language]['password_confirmation_empty'] + '</li>');
    }
    
    if(!isEmpty('register_password') && !isEmpty('register_confirm_password') && !isSameValue('register_password', 'register_confirm_password'))
    {
        err = true;
        $('#register_confirm_password_error_msg').append('<li>' + translations['messages'][language]['password_confirmation_not_match'] + '</li>');
    }
    
    if(!err)
    {
        conf = window.confirm("Do you want to register as " + $('#register_username').val() + "?");
        if(conf)
            $('#registerForm').submit();
    }
}
